package servlets.message;

import hibernate.method.MessageMethods;
import hibernate.model.Message;
import hibernate.util.HibernateUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.google.gson.Gson;

/**
 * Servlet implementation class RetrieveMsgBySender
 */
@WebServlet("/RetrieveMsgBySender")
public class RetrieveMsgBySender extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RetrieveMsgBySender() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	//PrintWriter out = response.getWriter();
		
		String sender  = request.getParameter("sender_id");
		int sender_id = Integer.parseInt(sender);
		
		
		response.setContentType("text/plain");
		SessionFactory sessionFactory = HibernateUtil
				.getSessionAnnotationFactory();
		Session s = sessionFactory.openSession();
		s.beginTransaction();
		MessageMethods msg_m = new MessageMethods();
		List<Message> list = new ArrayList<Message>();
		List<String> list2 = new ArrayList<String>();
		
		list = msg_m.list_by_sender(sessionFactory, s, sender_id);
		
		for (Message te1 : list) {
			list2.add(String.valueOf(te1.getMessage_id()));
		}

		String json = new Gson().toJson(list2);
		response.setContentType("application/json");
		response.getWriter().write(json);
	}

}
